/**
 */
//ipPort = '10.58.88.212:8080';
Ext.define('Server.Profile', {
	extend: 'Ext.panel.Panel',
	alias: 'server.profile',
    
    initComponent: function() {
		me_profile = this;
		comboBox = null;
	  	Ext.apply(this, {
			//id: '__profile_tab__',
			title: 'Profiles',
			closable: false,
			border: 0,
			height: '100%',
			width: '100%',
			layout: 'border',
			items: [{
				region: 'west',
				border: 0,
				width: '50%',
				height: '100%',
				split: true,
				items: [this.listGrid()]
			}, {
				region: 'center',
				border: 0,
				width: '100%',
				height: '100%',
				items: [this.detailGrid()]
			}]

		});
    	this.callParent(arguments);
	},
	/*
	load: function() {
		var me = this;
		var store = Ext.create('Ext.data.Store', {
			model: 'Profile'
		});
		store.load({
			callback: function(records, operation, success){
				var data = [];
				for (var i in records){
					var rec = records[i];
					data.push(rec.data);
				}
				me.listStore.loadData(data);
			}
		});
	},
	*/
	listGrid: function(){
		var me_profile = this;
    	me_profile.listCellEditing = Ext.create('Ext.grid.plugin.CellEditing', {
            clicksToEdit: 2
        });	
		me_profile.listGrid = Ext.create('Ext.grid.Panel', {
			//id: '__profile_list__',
			//title: 'Servers',
			//closable: false,
			height: '100%',
			//width: '100%',
			store: me_profile.listStore(),
			dockedItems: [{
                xtype: 'toolbar',
                dock: 'top',
                items: [{
                    text: 'New',
                    handler: function() {
                    	var groupName;
                    	Ext.Msg.prompt('Name', 'Please input new name:', function(btn, text) {
                            if (btn=='ok'){
                                var myObj = {
                                	ProfileGroup:{
                           				id: '',
                           				name: text
                                	}
                                };
                           		var jsonStr = Ext.encode(myObj);
                           		//me_profile.listGrid.setLoading(true);
                                Ext.Ajax.request({
                                	url: 'http://' + ipPort + '/bpcsaveprofilegroup/0',// + serverId,
                                	method: 'PUT',
                                	jsonData: jsonStr,
                                	success: function(response){
                                		var obj = Ext.decode(response.responseText);
                                		var profileGroupId = obj.profilegroup.id;
                                		me_profile.listGrid.store.load();
    									Ext.Ajax.request({
											url: 'http://' + ipPort + '/bpcmetadata',
											method: 'GET',
											success: function(response){
												var metaData = Ext.decode(response.responseText);
												var servers = new Array;
												if (metaData.servers != null) {
													if (!(metaData.servers.length)){
														servers[0] = metaData.servers;
													} else {
														servers = metaData.servers;
													};
												}
								/*				else 
													me_profile.listGrid.store.load();*/
												for (i = 0; i < servers.length; i ++){
													var myObj = {
							        						Profile:{
							        							id: '',
							        							groupId: profileGroupId,
							        							name: '',
							        							appset: '',
							        							application: '',
							        							username: '',
							        							password: '',
								        						serverId: servers[i].id		        						
							        						}
							        				};
							        				var jsonStr = Ext.encode(myObj);
							        				Ext.Ajax.request({
							        					url: 'http://' + ipPort + '/bpcsaveprofile/0',
							        					method: 'PUT',
							        					jsonData: jsonStr,
							        					success: function(response){
							        					},
							        					callback: function(){
							        						me_profile.listGrid.store.load();
							        					}
							        				});
												}
												
											}
										});
    									
                                	},
                                	callback: function(response){	
                                	}
                                });
                            };
                        });
                    }
                },{
                    text: 'Delete',
                    handler: function() {
                    	Ext.MessageBox.confirm('Delete', 'Do you really want to delete this profile?', function(id){
                    		if (id != 'yes'){
                    			return;
                    		} else {
                    			var m = me_profile.listGrid.getSelectionModel();
                    			var r = m.getLastSelected();
                    			if (r) {
                    				Ext.Ajax.request({
                    					method: 'DELETE',
                    					url: 'http://' + ipPort + '/bpcsaveprofilegroup/' + r.data.id
								})
								me_profile.listStore.remove(r);
                    			}
                    			else {
                    				alert('Please select a profile!');
                    			};
                    		};
                    	});
					}
                },{
                	text: 'Rename',
                	handler: function(){
                		var groupName;
                		var m = me_profile.listGrid.getSelectionModel();
						var r = m.getLastSelected();
						if (r) {
							Ext.Msg.prompt('Name', 'Please input new name:', function(btn, text) {
								if (btn=='ok'){
									var myObj = {
											ProfileGroup:{
												id: r.data.id,
												name: text
											}
									};
									var jsonStr = Ext.encode(myObj);
									Ext.Ajax.request({
										url: 'http://' + ipPort + '/bpcsaveprofilegroup/' + r.data.id,
										method: 'PUT',
										jsonData: jsonStr,
										success: function(response){
										},
										callback: function(){
											me_profile.listGrid.store.load();
										}
									});
								};
							});
						} else {
							alert('Please select a profile!');
						};
                	}
                	
                }

                ]
            }],
    		columns:[{
    			text:'ID',
    			dataIndex:'id',
				width: 30
    		}, {
    			text:'Profile',
    			dataIndex:'name',
				flex: true
    		}],
    		plugins: [me_profile.listCellEditing]
		});
		
		
		me_profile.listGrid.on( 'itemclick', function(view, record, item, index, e){
			var servers = record.profiles();
			me_profile.detailGrid.store.loadRecords(servers.getRange(0, servers.getCount()), {addRecords:false});
			me_profile.detailGrid.enable(true);

		});
		return me_profile.listGrid;
	},
	
	listStore: function(){
		var me_profile = this;
		me_profile.listStore = Ext.create('Ext.data.Store', {
			model: 'Profile'
		});
		me_profile.listStore.load();
		return me_profile.listStore;
	},
	
	detailGrid: function() {
		var me_profile = this;
    	var cellEditing = Ext.create('Ext.grid.plugin.CellEditing', {
            clicksToEdit: 1
        });	
		me_profile.detailGrid = Ext.create('Ext.grid.Panel', {
			//id: '__server_tab__',
			//title: 'Servers',
			//closable: false,
			height: '100%',
			disabled: 'true',
			//width: '100%',
			store: me_profile.detailStore(),
			dockedItems: [{
                xtype: 'toolbar',
                dock: 'top',
                items: [{
                	text: 'Edit',
                	handler: function(){
                		me_profile.serverWindow('edit');
                	}	
                }
                ]
            }],
    		columns:[{
    			text:'Server-ID',
    			dataIndex:'serverId',
    			flex: 1
//				flex: true,
//    			editor: {
//                    allowBlank: false
//                }
    		},{
    			text:'Appset',
    			dataIndex:'appset',
    			flex: 1
//				width: 150,
//    			editor: {
//                }
    		},{
    			text:'Application',
    			dataIndex:'application',
    			flex: 1
//				width: 150,
//    			editor: {
//                }
    		},{
    			text:'User Name',
    			dataIndex:'username',
    			flex: 1
//				width: 150,
//    			editor: {
//                }
//    		},{
//    			text:'Password',
//    			dataIndex:'password',
//    			inputType: 'password',
//    			flex: 1
////				width: 150,
////    			editor: {
////                }
    		}],
    		plugins: [cellEditing]			
		});
		
		return me_profile.detailGrid;
	},
	
	detailStore: function(){
		var me_profile = this;
		me_profile.detailStore = Ext.create('Ext.data.Store', {
			model: 'ProfileServer'
		});
		
		return me_profile.detailStore;
	},
	
	serverWindow: function(action){
		//var m = me_profile.listGrid.getSelectionModel().getLastSelected();
		//var groupId = m.data.id; 
		if (action == 'edit'){
			var n = me_profile.detailGrid.getSelectionModel();
			var r = n.getLastSelected();
			if (!(r)) {
				alert('Please select a line!');
				return;
			};
		};
		var win = Ext.create('Ext.window.Window',{
			title: 'ServerProfile',
		    closable: true,
		    closeAction: 'hide',
		    width: 600,
		    height: 230,
		    modal: true,
		    layout: 'border',
		    items: [{
		        region: 'west',
		    	width: 300,
		        border: 0,
		        items:[{
		        	xtype: 'textfield',
		        	padding: 3,
		        	width: 250,
		        	fieldLabel: 'Name',
		        	labelAlign: 'top',
		        	id: 'name'
		        },{
		        	xtype: 'textfield',
		        	padding: 3,
		        	width: 250,
		        	fieldLabel: 'Appset',
		        	labelAlign: 'top',
		        	id: 'appset'
		        },{
		        	xtype: 'textfield',
		        	padding: 3,
		        	width: 250,
		        	fieldLabel: 'Application',
		        	labelAlign: 'top',
		        	id: 'application'
		        },{
		        	xtype: 'container',
		        	padding: 3,
		        	layout: 'hbox',
		        	items:[{
		        		xtype: 'button',
		            	padding: 3,
		        		text: 'OK',
		        		handler: function(){
		        			
		        			var name = win.items.items[0].items.items[0].getValue();
		        			var appset = win.items.items[0].items.items[1].getValue();
		        			var application = win.items.items[0].items.items[2].getValue();
		        			var user = win.items.items[1].items.items[1].getValue();
		        			var password = win.items.items[1].items.items[2].getValue();
		        			
		        			if (action == 'edit'){
		        				var	id = r.data.id;
		        			} else {
		        				var id = 0;
		        			};
		        			server = win.items.items[1].items.items[0].getValue();
		        			var myObj = {
		        				Profile:{
		        					id: id,
		        					groupId: r.data.groupId,
		        					name: name,
		        					appset: appset,
		        					application: application,
		        					username: user,
		        					password: password,
			        				serverId: server		        						
		        				}
		        			};
		        			var jsonStr = Ext.encode(myObj);
		        			Ext.Ajax.request({
		        				url: 'http://' + ipPort + '/bpcsaveprofile/' + id,
		        				method: 'PUT',
		        				jsonData: jsonStr,
		        				success: function(response){
		        					me_profile.listGrid.store.load();
		        					win.close();
		        					me_server_server.profileTab.onServersModified();
		        				},
		        				callback: function(){
	
		        					
		        					
		        					
		        				}
		        			});	
		                }      		                	
		        	},{xtype:'hiddenfield', width: 5},{
		        		xtype: 'button',
		        		text: 'Cancel',
		        		handler: function(){
		        			win.close();
		        		}
		        	}]
		        }]
		    }, {
		    	region: 'center',
//		    	width: '50%',
		    	border: 0,
		        height: '100%',
		        items: [{
		        	xtype: 'textfield',
		        	padding: 3,
//		        	store: me_server.items.items[0].store,
//		        	multiSelect: true,
		        	width: 250,
		        	fieldLabel: 'Server-ID',
		        	labelAlign: 'top',
//		        	displayField: 'name',
		            id: 'serverId'
		        },{
		        	xtype: 'textfield',
		        	padding: 3,
		        	width: 250,
		        	fieldLabel: 'Username',
		        	labelAlign: 'top',
		        	id: 'user'
		        },{
		        	xtype: 'textfield',
		        	padding: 3,
		        	width: 250,
		        	inputType: 'password',
		        	fieldLabel: 'Password',
		        	labelAlign: 'top',
		        	id: 'password'
		        }]
		    }]
		});
		if (action == 'edit'){
			
			win.items.items[0].items.items[0].setValue(r.data.name);
			win.items.items[0].items.items[1].setValue(r.data.appset);
			win.items.items[0].items.items[2].setValue(r.data.application);
			win.items.items[1].items.items[1].setValue(r.data.username);
			win.items.items[1].items.items[2].setValue(r.data.password);
			var comboBox = win.items.items[1].items.items[0];
			comboBox.setValue(r.data.serverId);
			comboBox.setDisabled(true);
			
			var groupId = r.data.groupId;
			var id = r.data.id;
			
			
		};
		win.show();
	} 
	
	,onServersModified: function(servers) {
		var me_profile = this;
		me_profile.detailGrid.disable();
	}
//	onServersModified: function(servers) { //called when servers are modified
//		var me_profile = this;
//		me_profile.listStore.stickto = 'abcdefg';
//		me_profile.listStore.each(function(profile){ //keep existing ones
//			var finalServers = [];
//			profile.servers().each(function(pServer){
//				for(var i in servers) {
//					var server = servers[i];
//					if(server.get('id')==pServer.get('id')) {
//						finalServers.push(pServer);
//						break;
//					}					
//				}
//			});
//			for(var i in servers) { //add new/missing ones
//				var server = servers[i];
//				var serverID = server.get('id');
//				var notExisting = true;
//				for (var j in finalServers) {
//					if (serverID == finalServers[j].get('id')) {
//						notExisting = false;
//						break;
//					}
//				}
//				if (notExisting) {
//					var s = Ext.ModelManager.create( {profile_id:profile.get('id'), id:serverID, name:server.get('name')}, 'ProfileServer' );
//					finalServers.push(s);
//				}
//			}
//			var serversStore = profile.servers();
//			serversStore.removeAll();
//			serversStore.loadData(finalServers);
//			//serversStore.loadRecords(finalServers, {addRecords:false});
//		});
//	}
});



